import {inject, Injectable} from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, BehaviorSubject, tap } from 'rxjs';
import {
  LoginRequest,
  SignupRequest,
  AuthResponse,
  User,
  ApiResponse,
  ChangePasswordRequest,
  UpdateProfileRequest,
  ForgotPasswordRequest,
  ResetPasswordRequest,
  VerifyEmailRequest
} from '../models/auth.model';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private readonly TOKEN_KEY = 'blog_token';
  private readonly USER_KEY = 'blog_user';

  // 当前用户状态
  private currentUserSubject = new BehaviorSubject<User | null>(this.getUserFromStorage());
  public currentUser$ = this.currentUserSubject.asObservable();
  private http = inject(HttpClient);



  /**
   * 用户登录
   */
  login(loginData: LoginRequest): Observable<AuthResponse> {
    return this.http.post<AuthResponse>('/auth/signin', loginData)
      .pipe(
        tap(response => {
          if (response.status && response.data.token) {
            this.setToken(response.data.token);
            this.setUser(response.data.user);
            this.currentUserSubject.next(response.data.user);
          }
        })
      );
  }

  /**
   * 用户注册
   */
  signup(signupData: SignupRequest): Observable<ApiResponse> {
    return this.http.post<ApiResponse>('/auth/signup', signupData);
  }

  /**
   * 获取当前用户信息
   */
  getCurrentUser(): Observable<ApiResponse<{ user: User }>> {
    return this.http.get<ApiResponse<{ user: User }>>('/auth/current-user')
      .pipe(
        tap(response => {
          if (response.status && response.data?.user) {
            this.setUser(response.data.user);
            this.currentUserSubject.next(response.data.user);
          }
        })
      );
  }

  /**
   * 修改密码
   */
  changePassword(data: ChangePasswordRequest): Observable<ApiResponse> {
    return this.http.put<ApiResponse>('/auth/change-password', data);
  }

  /**
   * 更新用户信息
   */
  updateProfile(data: UpdateProfileRequest): Observable<ApiResponse<{ user: User }>> {
    return this.http.put<ApiResponse<{ user: User }>>('/auth/update-profile', data)
      .pipe(
        tap(response => {
          if (response.status && response.data?.user) {
            this.setUser(response.data.user);
            this.currentUserSubject.next(response.data.user);
          }
        })
      );
  }

  /**
   * 发送邮箱验证码
   */
  sendVerificationEmail(email: string): Observable<ApiResponse> {
    return this.http.post<ApiResponse>('/auth/send-verification-email', { email });
  }

  /**
   * 验证邮箱
   */
  verifyEmail(data: VerifyEmailRequest): Observable<ApiResponse> {
    return this.http.post<ApiResponse>('/auth/verify-user', data);
  }

  /**
   * 发送忘记密码验证码
   */
  sendForgotPasswordCode(email: string): Observable<ApiResponse> {
    return this.http.post<ApiResponse>('/auth/forgot-password-code', { email });
  }

  /**
   * 重置密码
   */
  resetPassword(data: ResetPasswordRequest): Observable<ApiResponse> {
    return this.http.post<ApiResponse>('/auth/recover-password', data);
  }

  /**
   * 登出
   */
  logout(): void {
    this.removeToken();
    this.removeUser();
    this.currentUserSubject.next(null);
  }

  /**
   * 检查是否已登录
   */
  isLoggedIn(): boolean {
    return !!this.getToken();
  }

  /**
   * 获取token
   */
  getToken(): string | null {
    return localStorage.getItem(this.TOKEN_KEY);
  }

  /**
   * 设置token
   */
  private setToken(token: string): void {
    localStorage.setItem(this.TOKEN_KEY, token);
  }

  /**
   * 移除token
   */
  private removeToken(): void {
    localStorage.removeItem(this.TOKEN_KEY);
  }

  /**
   * 获取用户信息
   */
  private getUserFromStorage(): User | null {
    const userStr = localStorage.getItem(this.USER_KEY);
    return userStr ? JSON.parse(userStr) : null;
  }

  /**
   * 设置用户信息
   */
  private setUser(user: User): void {
    localStorage.setItem(this.USER_KEY, JSON.stringify(user));
  }

  /**
   * 移除用户信息
   */
  private removeUser(): void {
    localStorage.removeItem(this.USER_KEY);
  }


}
